<?php
/**
 *     
 *  生成订单 
 */
//require_once("IapppayCpSyncForPHP/base.php");
require_once("alipay/config.php");
require_once("IapppayCpSyncForPHP/base.php");
require_once("IapppayCpSyncForPHP/config.php");

class ApplyABPay extends APIBase {
	public $tag = "ApplyABPay";
	
	public function before() {
		$this->initMysql();
		return true;
	}
		
	//生成随机24位订单号
	protected function createOrderId ($length = 24) {
		$seed=md5(microtime());
		$pwd='';
		for($i=0;$i<$length;$i++){
			$pwd.=$seed{mt_rand(0,31)};
		}
		$hash=md5($pwd);
		return substr($hash,0,$length);
	}
	
	protected function paraFilter($para) {
	  $str='';	
	  foreach($para as $key=>$val){
	     if($key=='sign_type' || $key == 'sign'){
		   continue;
		  }
	   else{
	     if($str ==''){
		   $str =$key.'='.'"'.$val.'"';
	     }else{
		   $str =$str.'&'.$key.'='.'"'.$val.'"';
		 }	
		
	     }
        }
		return $str;
    }
	
    protected function argSort($para) {
		ksort($para);
		reset($para);
		return $para;
     }
    //RSA签名
    protected function sign($data) {
	
	   //读取私钥文件
	   //$sign = 111;
	   $path = dirname(__FILE__);
	   $priKey =  file_get_contents($path."/alipay/rsa_private_key.pem");//私钥文件路径
	  //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
	   $res = openssl_get_privatekey($priKey);
	  //调用openssl内置签名方法，生成签名$sign
	   openssl_sign($data, $sign, $res);
	  //释放资源 
	   openssl_free_key($res);
	   //base64编码
	   $sign = base64_encode($sign);
	   return $sign;
	 
	}


     	
	public function logic() {
		/*if (!isset($this->param['version'])) {
			$this->returnError(310, "param must be needed");
		}
*/    
		if (!isset($this->param['goodsid'])) {
			$this->returnError(310, "goodsid must be needed");
		}
		
		//支付类型
		if (!isset($this->param['pay_type'])) {
			$this->returnError(310, "pay_type must be needed");
		}

		$where['id'] = (int)$this->param['goodsid'];
		$good = $this->mysql->select('goods','*',$where);

		if(!count($good)) {     
			$this->returnError(310, "goodsid is not exists");
		}
        
	
		$payinfo['uid'] = (int) $this->uid;
		$payinfo['price'] = (float) $good[0]['buy_money'];
		$payinfo['pay_type'] = (int) $this->param['pay_type'];
		$payinfo['goodsid'] = (int) $this->param['goodsid'];
		$payinfo['version'] = 0;
		$payinfo['create_time'] = time();
		$payinfo['type'] = 0;
		$payinfo['is_send'] = 0;
		$payinfo['orderid'] = $this->createOrderId();
		$sign  = $this->mysql->insert('applypay', $payinfo);

		if ($sign) {
			//其它 购买方式
			//$path = dirname(__FILE__);
			if((int) $this->param['pay_type']==3){
				//file_put_contents($path.'/alipay/pay.txt',$this->param['pay_type']);
				/*global $cpvkey;
				$data = array();
				$data['cporderid'] = $payinfo['orderid'];
				$data['price'] = (int)($payinfo['price']*100);
				$data['cpprivateinfo'] = "cpprivateinfo123456";
				$data['notifyurl'] = stripslashes(Config::$ab_pay_confing["notify_url"]);
				$data['appuserid'] = (string)$payinfo['uid'];
				$data['appid'] = Config::$ab_pay_confing["app_id"];
				$data['waresid'] = (int)$payinfo['goodsid'];
				$reqData = composeReq($data, $cpvkey);*/
				//$this->returnData($reqData);
				$ali = array(
					  'service' => 'mobile.securitypay.pay',
					  'partner' => Alionfig::$partner,// 签约合作者身份ID
					  '_input_charset' => 'utf-8',
					  'sign_type' => 'RSA',
					  'sign' => '',
					  'notify_url' => Config::$alipay_notify_url,//回调地址
					  'out_trade_no' => $payinfo['orderid'],//商户网站唯一订单号
					  'subject' => $good[0]['name'],//商品名称
					  'payment_type' => 1,//支付类型
					  'seller_id' => Alionfig::$seller_id,//支付宝账号
					  'total_fee' => (float) $good[0]['rmb'],//总金额
					  'body' => $good[0]['name']//商品详情
					  //'it_b_pay'=>'30m',
					 // 'return_url'=>'m.alipay.com'
				);
                $ali = $this->argSort($ali);

                $str = $this->paraFilter($ali);
                $sign = urlencode($this->sign($str));
                $str = $str.'&sign='.'"'.$sign.'"'.'&sign_type='.'"'.$ali['sign_type'].'"';//传给支付宝接口的数据
			    
                //file_put_contents('./alipay/pay.txt',$str,FILE_APPEND);
				Config::$logger->info($this->tag, 'aip---'.$str);
				$this->returnData(array('orderinfo'=>$str,'notifyurl'=>'','pay_type'=>3));
				
			//ios 购买	
			}elseif((int) $this->param['pay_type']==2){
				
				$str = "0#$payinfo[orderid]#$payinfo[price]#$apple_id";
				$this->returnData(array('orderinfo'=>$str,'pay_type'=>2,'notifyurl'=>stripslashes(Config::$apple_pay_confing["apple_notify_url"])));
			}elseif((int) $this->param['pay_type']==4){
				unset($payinfo['version']);
				unset($payinfo['create_time']);
				unset($payinfo['type']);
				unset($payinfo['is_send']);
				//{\"uid\":4889,\"price\":12,\"pay_type\":4,\"goodsid\":1,\"orderid\":\"7925a85e17be21046af5ac93\"}
				//$str = "0#$payinfo[orderid]#$payinfo[price]#$apple_id";
				Config::$logger->info($this->tag, '4aip---'.json_encode(array('orderinfo'=>$payinfo,'notifyurl'=>stripslashes(Config::$tx_notify_url))));

				$this->returnData(array('orderinfo'=>'{"uid":'.$payinfo['uid'].',"price":'.$payinfo['price'].',"pay_type":'.$payinfo['pay_type'].',"goodsid":'.$payinfo['goodsid'].',"orderid":"'.$payinfo['orderid'].'"}','notifyurl'=>stripslashes(Config::$tx_notify_url)));
			}elseif((int) $this->param['pay_type']==1){//爱贝支付
				$orderUrl = ibconfig::$orderUrl;
			    $appkey = ibconfig::$appkey;
			    $platpkey = ibconfig::$platpkey;
			    //$transid;
			    $appid = ibconfig::$appid;
				$orderReq['waresid'] = (int) $this->param['goodsid'];
                $orderReq['cporderid'] = (string)$payinfo['orderid']; //确保该参数每次 都不一样。否则下单会出问题。
                $orderReq['price'] = 0.1;   //单位：元
                $orderReq['currency'] = 'RMB';
                $orderReq['appuserid'] = (string) $this->uid;//玩家id
                $orderReq['notifyurl'] = 'http://120.76.189.164/zjgpay/iappPayTrade.php';
				//组装请求报文  对数据签名
                $reqData = ipbase::composeReq($orderReq, $appkey);
				 //发送到爱贝服务后台请求下单
                $respData = ipbase::request_by_curl($orderUrl, $reqData);
			    Config::$logger->info($this->tag, "respData:".$respData);
				//验签数据并且解析返回报文
                if(!ipbase::parseResp($respData, $platpkey, $respJson)) {
		           Config::$logger->info($this->tag, "parseResp:failed");
                }else{
					
    	        //echo "success";
    	        //echo "服务端下单完成，trasnid:<br/>";
    	        // print_r($respJson);
                // 下单成功之后获取 transid
		        Config::$logger->info($this->tag, "trasnid:success");
    	        $transid=$respJson->transid;
                }      
			$reorderinfo = array('transid'=>$transid,'appid'=>$appid);			
			$this->returnData($reorderinfo);
			}
			
		} else {
			$this->returnError(301,'create order failed!');
		}
	}
    
	public function after() {
		$this->deinitMysql();
	}
}

?>
